'use strict';
const db = uniCloud.database()

exports.main = async (event, context) => {
	try {
		const { keyword = '' } = event
		const collection = db.collection('saige_Data')
		
		// 构建搜索条件
		const query = collection.where(db.command.or([
			{
				owner: new RegExp(keyword, 'i')
			},
			{
				foot_ring_number: new RegExp(keyword, 'i')
			},
			{
				address: new RegExp(keyword, 'i')
			},
			{
				rank: new RegExp(keyword, 'i')
			}
		]))
		
		const res = await query
			//.orderBy('lastRank', 'asc')
			.limit(5)
			.get()
		
		// 过滤掉_id字段
		const filteredData = res.data.map(item => {
			const { _id, ...rest } = item
			return rest
		})
		
		return {
			code: 0,
			data: filteredData,
			msg: '搜索成功'
		}
	} catch (e) {
		return {
			code: -1,
			data: null,
			msg: '搜索失败：' + e.message
		}
	}
}